const {faviconGenerator} = require('favicon-generator');
const fs = require('fs');

// const sharp = require('sharp');

const path = require("path");
const  JSZIP = require("jszip");
const { resolve } = require('path');


const zip = new JSZIP();


const readDir = (obj, nowPath) =>  {
    let files = fs.readdirSync(nowPath);//读取目录中的所有文件及文件夹（同步操作）
      files.forEach(function (fileName, index) {//遍历检测目录中的文件
       
         let fillPath = nowPath + "/" + fileName;
         let file = fs.statSync(fillPath);//获取一个文件的属性
         if (file.isDirectory()) {//如果是目录的话，继续查询
             let dirlist = zip.folder(fileName);//压缩对象中生成该目录
             readDir(dirlist, fillPath);//重新检索目录文件
         } else {
             obj.file(fileName, fs.readFileSync(fillPath));//压缩目录添加文件
         }
     });
 }


 const  startZIP =() =>  {
     return new Promise(() => {
        var currPath = './';//文件的绝对路径 当前当前js所在的绝对路径
        var targetDir = path.join(currPath, "pwa-manifast");
        readDir(zip, targetDir);
        zip.generateAsync({//设置压缩格式，开始打包
            type: "nodebuffer",//nodejs用
            // compression: "DEFLATE",//压缩算法
            // compression: "GZIP",
            // compressionOptions: {//压缩级别
            //     level: 9
            // }
        }).then(function (content) {
            const zipAllFile = fs.writeFileSync(currPath + "/pwa-manifast.zip", content, "utf-8");//将打包的内容写入 
            
            resolve('zipAllFile');
        });
     })
    
}


/**
 * manifast模版
 * @param {*} pathDir 
 * @returns 
 */

const createManifastTemplate = (name, short_name, theme_color, background_color, display, Scope, start_url) => {
    return `{
    "name": "${name}",
    "short_name": "${short_name}",
    "theme_color": "${theme_color}",
    "background_color": "${background_color}",
    "display": "${display}",
    "Scope": "${Scope}",
    "start_url": "/${start_url}",
    "orientation": "portrait-primary",
    "icons": [{
        "src": "imgs/icon-72x72.png",
        "sizes": "72x72",
        "type": "image/png"
    },{
        "src": "imgs/icon-96x96.png",
        "sizes": "96x96",
        "type": "image/png"
    },{
        "src": "imgs/icon-114x114.png",
        "sizes": "114x114",
        "type": "image/png"
    },{
        "src": "imgs/icon-128x128.png",
        "sizes": "128x128",
        "type": "image/png"
    },{
        "src": "imgs/icon-144x144.png",
        "sizes": "144x144",
        "type": "image/png"
    },{
        "src": "imgs/icon-152x152.png",
        "sizes": "152x152",
        "type": "image/png"
    },{
        "src": "imgs/icon-192x192.png",
        "sizes": "192x192",
        "type": "image/png"
    },{
        "src": "imgs/icon-384x384.png",
        "sizes": "384x384",
        "type": "image/png"
    },{
        "src": "imgs/icon-256x256.png",
        "sizes": "256x256",
        "type": "image/png"
    },{
        "src": "imgs/icon-512x512.png",
        "sizes": "512x512",
        "type": "image/png"
    }],
    "splash_pages": null
}`;
}

/**
 * 创建目录
 * @param {*} pathDir 
 * @returns 
 */

const createDirFn = (pathDir) => {
    return new Promise((resolve, reject) => {
        fs.mkdir(`./${pathDir}/`,function(err){
            if (err) {
                return console.error(err);
            }
            resolve();
         });
    }) 
}

/**
 * 递归删除文件夹及目录
 * @param {*} pathDir 
 */

const deleteDirFile = (pathDir) => {

    var dirList = fs.readdirSync(pathDir);

    dirList.forEach(function(fileName) {
        
        let fileOrDir = `${pathDir}/${fileName}`;
        

        if(fs.lstatSync(fileOrDir).isDirectory()) {
            deleteDirFile(fileOrDir)
        } else {
            fs.unlinkSync(fileOrDir); 

        }



    });
    fs.rmdirSync(pathDir);
}
/**
 * 创建目录
 * @returns 
 */

const createDir = async (pathDir) => {
    //检查路径是否存在
    if (fs.existsSync(pathDir)) {
        deleteDirFile(pathDir);
        await createDirFn(pathDir);
    } else {
        await createDirFn(pathDir);
    }
}

/**
 * 创建文件
 * @param {String} name 
 * @param {string} short_name 
 * @param {string} theme_color 
 * @param {string} background_color 
 * @param {string} display 
 * @param {string} Scope 
 * @param {string} start_url 
 * @returns 
 */
const createManifast = (name, short_name, theme_color, background_color, display, Scope, start_url) => {
    return new Promise((resolve, reject)=> {
        // fs.writeFile();

        let template = createManifastTemplate(name, short_name, theme_color, background_color, display, Scope, start_url);

        fs.writeFile(`./pwa-manifast/manifast.json`, template, function(err) {
            if(err) {
                return console.log(err);
            }
            
            resolve('创建成功');
        });


    })
}

/**
 * 创建img目录
 * @returns 
 */
const createImgForlder = (pathDir) => {
    return new Promise((resolve, reject) => {
        fs.mkdir(`./${pathDir}/`,function(err){
            if (err) {
                return console.error(err);
            }
            resolve(pathDir);
         });
    })
}


/**
 * 图片尺寸数组
 * @returns 
 */
const imgSize = () => {
    const arr = [{
        size: 72,
        imgName: 'icon-72x72'
    },{
        size: 96,
        imgName: 'icon-96x96'
    },{
        size: 114,
        imgName: 'icon-114x114'
    },{
        size: 128,
        imgName: 'icon-128x128'
    },{
        size: 144,
        imgName: 'icon-144x144'
    },{
        size: 152,
        imgName: 'icon-152x152'
    },{
        size: 192,
        imgName: 'icon-192x192'
    },{
        size: 384,
        imgName: 'icon-384x384'
    },{
        size: 256,
        imgName: 'icon-256x256'
    },{
        size: 512,
        imgName: 'icon-512x512'
    },{
        size:114,
        imgName:"touch-icon-iphone-114"
    },{
        size:114,
        imgName:"touch-icon-iphone-114"
    },{
        size:114,
        imgName: "touch-icon-ipad-144"
    }];
    return arr;
}



/**
 * 生成不同尺寸的png
 * @param {string} pathImg 
 * @returns 
 */
const createMoreImg = (pathImg) => {
    return new Promise( async (resolve, reject)=> {
        if (fs.existsSync(`./${pathImg}`)) {
             imgSize().forEach(async (item) => {
                //  sharp(`./${pathImg}`).resize(item.size).toFile(`./pwa-manifast/img/icon-${item.imgName}.png`, (err) => {
                //     if (err) {
                //         throw err;
                //     }
                // })


                let favicons = await faviconGenerator(`./${pathImg}`, [
                    {
                        width: item.size,
                        format: 'png',
                    }
                ])

                await fs.writeFileSync(`./pwa-manifast/img/icon-${item.imgName}.png`, favicons[0].buffer)
                

            })
            resolve();



            resolve();
        } else {
            reject();
            console.log('不存在');
        }
        
    });
}

//demo页模板
const demoTpl = () => {
    
    
    const tpl = `
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
        
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="default">
        <meta name="apple-mobile-web-app-title" content="demo">

        <meta name="application-name" content="demo" />
        <meta name="msapplication-TileColor" content="#222">
        <meta name="msapplication-square70x70logo" content="img/icon-72x72.png" />
        <meta name="msapplication-square150x150logo" content="img/icon-144x144.png" />
        <meta name="msapplication-square310x310logo" content="img/icon-256x256.png" />

        <title>demo</title>

        <link rel="manifest" href="/manifest.json">
        <!-- Standard iPhone -->
        <link rel="apple-touch-icon" sizes="57x57" href="imgs/icon-114x114.png">
        <!-- Retina iPhone -->
        <link rel="apple-touch-icon" sizes="114x114" href=“imgs/touch-icon-iphone-114.png">
        <link rel="apple-touch-icon" href="img/icon-256x256.png">
        <!-- Standard iPad -->
        <link rel="apple-touch-icon" sizes="72x72" href=“imgs/touch-icon-ipad-144.png">
        <!-- Retina iPad -->
        <link rel="apple-touch-icon" sizes="144x144" href=“imgs/touch-icon-ipad-144.png">

        <!-- 滚动加载  -->
        <style>
        * {
            margin:0;
            padding:0;
        }
        </style>
        <script>
            (function (doc, win) {
                var docEl = doc.documentElement,
                    resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
                    recalc = function () {
                        var clientWidth = docEl.clientWidth;
                        if (!clientWidth) return;
                        docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
                    };
                if (!doc.addEventListener) return;
                win.addEventListener(resizeEvt, recalc, false);
                doc.addEventListener('DOMContentLoaded', recalc, false);
            })(document, window);

        </script>
    </head>
    <body>
        首页
    </body>
</html>
`

return tpl;

}


/**
 * 创建demo页
 */
const createDemoPage = () => {
  
    const tpl = demoTpl();

    return new Promise((resolve, reject) => {

        fs.writeFile(`./pwa-manifast/index.html`, tpl, function(err) {
            if(err) {
                return console.log(err);
            }
            
            resolve('创建成功');
        });
    

    })


}


const startTpl = () => {

    const tpl = `
    <html lang="en"><script></script><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin:0px;
            padding:0px;
        }
        .startPage {
            display: flex;
            align-items: center;
            justify-content: center;
            height:100vh;
        }
        .startPage-logo {
            width:152px;
        }
    </style>
</head>
<body>
    <div class="startPage">
        <img class="startPage-logo" src="imgs/icon-152x152.png">
    </div>
    <script>
        setTimeout(()=> {
            window.location.href= "/index.html";
        }, 3000)
    </script>

    <div id="janus-extension-installed" style="display: none;"></div></body></html>
    `;
    return tpl;
}

/**
 * 启动页面
 */
const startPage = (fileName) => {
    const tpl  = startTpl();
    return new Promise((resolve, reject)=> {
        fs.writeFile(`./pwa-manifast/${fileName}`, tpl, function(err) {
            if(err) {
                return console.log(err);
            }
            
            resolve('创建成功');
        });
    })
    
}





const createIconFolder = async (pathDir) => {
    if (fs.existsSync(pathDir)) {
        deleteDirFile(pathDir);
        await createDirFn(pathDir);
    } else {
        await createDirFn(pathDir);
    }
}

const createIcoImg = (icoFileName,size, img) => {

    // console.log(icoFileName,size, img);
    return new Promise( async (resolve, reject)=> {


        // console.log(`./ico/${icoFileName}`);


        // console.log(fs.existsSync(`./ico/${icoFileName})`));
        // console.log(fs.existsSync(`${img}`));
        // console.log(fs.existsSync(`./arrow.png`));


        
        
        
        let favicons = await faviconGenerator(`${img}`, [
            {
                width: size,
                format: 'ico',
            },
        ])
    
        await fs.writeFileSync(`./ico/${icoFileName}`, favicons[0].buffer)
        resolve();
    
    });
}

//启动页面
module.exports.startPage = startPage;
//创建demo页面
module.exports.createDemoPage = createDemoPage;
//创建更多图片
module.exports.createMoreImg = createMoreImg;
//创建文件夹
module.exports.createDir = createDir;

//创建文件
module.exports.createManifast = createManifast;

//创建img目录
module.exports.createImgForlder = createImgForlder;

//压缩
module.exports.startZip = startZIP;

//创建ico目录
module.exports.createIconFolder = createIconFolder;

//创建ico文件
module.exports.createIcoImg = createIcoImg;